/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

 //自己动手实现方法
// class Solution {
// public:
//     ListNode* removeNthFromEnd(ListNode* head, int n) {

//         ListNode* ans = head;
//         ListNode* cur = head;
//         int count = 0;
//         while (cur) {
//             cur = cur->next;
//             count++;
//         }
//         if(count==1)return nullptr;
//         if (n == count) {
//             ListNode* tmp = head->next;
//             delete head;
//             ans = tmp;
//         } else {
//             cur = head;
//             while (count - n - 1 > 0) {
//                 cur = cur->next;
//                 count--;
//             }
//             if (cur->next->next) {
//                 ListNode* next = cur->next->next;
//                 delete cur->next;
//                 cur->next = next;
//             } else {
//                 cur->next = nullptr;
//             }
//         }

//         return ans;
//     }
// };

//第二种方法自己写出来的
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* ans=head;
        ListNode* fast=head;
        ListNode* slow=head;
        while(n--)
        {
            fast=fast->next;
        }
        if(!fast) 
        {
            ListNode* tmp=head->next;
            delete head;
            ans=tmp;
            return ans;
        }
        while(fast->next)
        {
            fast=fast->next;
            slow=slow->next;
        }
        if(slow->next->next)
        {
            ListNode* tmp=slow->next->next;
            delete slow->next;
            slow->next=tmp;
        }
        else
        {
            delete slow->next;
            slow->next=nullptr;
        }
        return ans;
    }
};
